package com.loe.view.viewpager;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

import com.loe.view.R;

import java.util.ArrayList;
import java.util.List;

public class SlideTabView extends HorizontalScrollView implements View.OnClickListener
{
    public SlideTabView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        init(context, context.obtainStyledAttributes(attrs, R.styleable.SlideTabView));
    }

    public SlideTabView(Context context, AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
        init(context, context.obtainStyledAttributes(attrs, R.styleable.SlideTabView, defStyleAttr, 0));
    }

    @SuppressLint("NewApi")
    public SlideTabView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
    {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, context.obtainStyledAttributes(attrs, R.styleable.SlideTabView, defStyleAttr, defStyleRes));
    }

    private FrameLayout frame;
    private LinearLayout tab;
    private View line;

    /** line水平padding */
    private int linePaddingH = 20;

    public int index = 0;

    private float X, W;

    private int lineLen = 0;

    private boolean isAuto = true;

    private boolean isWorm = true;

    private FrameLayout.LayoutParams lineParams;

    private ViewPager viewPager;

    private ArrayList<TabItem> items;

    private void init(final Context context, TypedArray typedArray)
    {
        items = new ArrayList<>();

        frame = new FrameLayout(getContext());
        tab = new LinearLayout(getContext());
        tab.setOrientation(LinearLayout.HORIZONTAL);
        frame.addView(tab, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        line = new View(getContext());
        line.setBackgroundResource(R.color.colorPrimary);
        frame.addView(line, ViewGroup.LayoutParams.MATCH_PARENT, px(2));
        lineParams = (LayoutParams) line.getLayoutParams();

        addView(frame, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);

        setScrollBarSize(0);
    }

    public void add(FragTabItem item)
    {
        tab.addView(item.view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
    }

    public void setItems(List<FragTabItem> items)
    {
        this.items.clear();
        for (FragTabItem item : items)
        {
            add(item);
        }
        this.items.addAll(items);

        // items事件
        for (int i = 0; i < items.size(); i++)
        {
            items.get(i).view.setOnClickListener(this);
        }
    }

    private int px(float dp)
    {
        return (int) (dp * Resources.getSystem().getDisplayMetrics().density + 0.5);
    }

    /**
     * tab切换滚动
     */
    public void onScrolled(int i, float scale)
    {
        try
        {
            View nowView = items.get(i).view;
            View nextView = items.get(i + 1).view;
            // 蠕虫
            if (isWorm)
            {
                if (isAuto)
                {
                    if (scale < 0.5)
                    {
                        X = nowView.getX();
                        W = nowView.getWidth() + nextView.getWidth() * scale * 2;
                    }
                    else
                    {
                        float nW = nowView.getWidth() * (scale - 0.5f) * 2;
                        X = nowView.getX() + nW;
                        W = nowView.getWidth() + nextView.getWidth() - nW;
                    }
                }
                else
                {
                    if (scale < 0.5)
                    {
                        X = nowView.getX() + (nowView.getWidth() - lineLen) / 2f;
                        W = lineLen + (nextView.getWidth() + nowView.getWidth()) * scale;
                    }
                    else
                    {
                        X = nowView.getX() + (nowView.getWidth() - lineLen) / 2f + (nextView.getWidth() + nowView.getWidth()) * (scale - 0.5f);
                        W = lineLen + (nextView.getWidth() + nowView.getWidth()) * (1 - scale);
                    }
                }
            }
            // 普通
            else
            {
                if (isAuto)
                {
                    X = nowView.getX() + nowView.getWidth() * scale;
                    W = nowView.getWidth() + (nextView.getWidth() - nowView.getWidth()) * scale;
                }
                else
                {
                    X = nowView.getX() + (nowView.getWidth() - W) / 2 + (nextView.getWidth() + nowView.getWidth()) / 2f * scale;
                    W = lineLen;
                }
            }
            updateLine();
        } catch (Exception e)
        {
        }
    }

    /**
     * 设置滑动位置
     */
    private void updateLine()
    {
        int x = (int) X + linePaddingH + 1;
        int w = (int) W - linePaddingH * 2;
        lineParams.setMargins(x, 0, 0, 0);
        lineParams.width = w;
        line.setLayoutParams(lineParams);

        smoothScrollTo((int) (X - 2 - (getWidth() - W) / 2), 0);
    }

    /** 点击tab项 */
    @Override
    public void onClick(View view)
    {
        for (int i = 0; i< items.size(); i++)
        {
            TabItem item = items.get(i);
            if (view.equals(item.view))
            {
                // 更新选项卡
                selectItem(i);
                // 更新页面
                if(viewPager != null) viewPager.setCurrentItem(i);
            }
        }
    }

    /**
     * 选择页面
     */
    public void select(int i)
    {
        // 更新选项卡
        selectItem(i);
        // 更新页面
        if(viewPager != null) viewPager.setCurrentItem(i);
    }

    /**
     * 建立单个选中状态
     */
    private void selectItem(int index)
    {
        // 清除所有选择状态
        for (TabItem item : items)
        {
            item.onSelect(false);
        }
        // 添加单个选择状态
        items.get(index).onSelect(true);
    }

    public ArrayList<TabItem> getItems()
    {
        return items;
    }

    public FrameLayout getFrame()
    {
        return frame;
    }

    public LinearLayout getTab()
    {
        return tab;
    }

    public View getLine()
    {
        return line;
    }

    public ViewPager getViewPager()
    {
        return viewPager;
    }

    public void setLinePaddingH(int linePaddingH)
    {
        this.linePaddingH = linePaddingH;
    }

    public void setViewPager(ViewPager viewPager)
    {
        this.viewPager = viewPager;
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener()
        {
            @Override
            public void onPageSelected(int index)
            {
                selectItem(index);
                SlideTabView.this.index = index;
            }

            @Override
            public void onPageScrolled(int i, float scale, int arg2)
            {
                onScrolled(i, scale);
            }

            @Override
            public void onPageScrollStateChanged(int arg0)
            {
            }
        });
    }
}